import asyncio
import datetime
import json
import random
import time

# import grequests
import aiohttp
import requests
import ser as ser
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
import multiprocessing as mp
# Create your views here.
# class
from rest_framework.serializers import ModelSerializer
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet, ModelViewSet

from testviewset.models import User, Book
from testviewset.serial import UserSer, UserPage
from utils.auth import WebAuth
from utils.utils import getData, data2ObjDict, requestData


class UserSer(ModelSerializer):
    class Meta:
        model = User
        fields = ['user', 'pwd', 'tel']


class BookSer(ModelSerializer):
    class Meta:
        model = Book
        fields = ['name', 'author', 'page', 'pubtime']


class TestUserViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSer


class testAuth(APIView):
    # authentication_classes = [WebAuth]

    def get(self, request):
        user = request.user
        # print(user)
        data = getData(request)
        # user.__dict__.update(tel=data["tel"])
        # print(data.__dict__)
        # print(data.__dict__)
        # print(type(user))
        # user.save()
        # book_set = Book.objects.filter(**data2ObjDict(data, Book())).values("name", "author", "page")

        # book_set = Book.objects.filter(**data2ObjDict(data, Book())).values("name", "author", "page")
        # print(book_set.query)
        # requestData('get', '', {})

        # book_set = Book.objects.filter(**data2ObjDict(data, Book()))
        # book_set = Book.objects.all()
        # print(book_set)
        # ser = MySer(instance=book_set)
        # print(ser.data)
        a = User.objects.all()
        user_ser = UserSer(instance=a, many=True)
        p = UserPage()
        p_obj = p.paginate_queryset(queryset=user_ser.data, request=request, view=self)
        print(a)
        # requestData('get', '', {})
        # return HttpResponse(data["param1"])
        # return HttpResponse(json.dumps(list(book_set)))
        return p.get_paginated_response(p_obj)
        # return JsonResponse({'test': 'test'}, content_type='text/html')

    def post(self, request):
        user = request.user.__dict__
        user.pop('_state')
        print(user)
        data = getData(request)
        return JsonResponse({'test': 'test'})


def Unicode():
    val = random.randint(0x4e00, 0x9fbf)
    return chr(val)


def GBK2312():
    head = random.randint(0xb0, 0xf7)
    body = random.randint(0xa1, 0xfe)
    val = f'{head:x} {body:x}'
    str = bytes.fromhex(val).decode('gb2312')
    return str


# 使用aiohttp
# https://www.zhihu.com/question/20145091
class zhuanfa(APIView):

    def get(self, request):
        # word = Unicode()
        a = 1
        word = GBK2312()
        s_c_list = []
        words = ['十年', '富士山下', '爱情转移', '海阔天空']
        for word in words:
            search_url = 'http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=' + word + '&type=1&offset=0&total=true&limit=20'
            print(word)

            if a:
                try:
                    data = requests.get(search_url).json()
                    print(data)
                    songs = data["result"]["songs"]
                    for s in songs:
                        comments_url = f'https://music.163.com/api/v1/resource/comments/R_SO_4_' + str(s['id']) + '?limit=20&offset=0'
                        data = requests.get(comments_url).json()
                        comments = data["hotComments"]
                        for c in comments:
                            s_c_list.append({'song_name': s['name'], 'content': c["content"], "pic": c["user"]["avatarUrl"],
                                             "nick": c["user"]["nickname"]})
                except Exception as e:
                    print(str(e))
                    print(s_c_list)
                    return JsonResponse(s_c_list, safe=False)
                    # c_list.append({s['name']: s_c_list})
                print(s_c_list)
            else:
                s_c_list = [{'song_name': 'Belly Dancer', 'content': '有女生喜欢这样的歌吗[色]', 'pic': 'http://p2.music.126.net/0NWiDqkx6Q1F59Lpo3PIJg==/109951166177193903.jpg', 'nick': 'yytt_qDF6'}, {'song_name': 'Belly Dancer', 'content': '《关于我一秒切换软件加入歌单这件事》', 'pic': 'http://p2.music.126.net/x0bsMvE08TasF2mnSorDtA==/109951167060119260.jpg', 'nick': 'Leebass-'}, {'song_name': 'Belly Dancer', 'content': '《我的间谍爸爸和杀手妈妈😎😎》', 'pic': 'http://p2.music.126.net/ksGms5WknwlyFrV2CLuXPw==/109951164587829880.jpg', 'nick': '尼康_0'}]
        return JsonResponse(s_c_list, safe=False)


class zhuanfa2(APIView):

    def get(self, request):
        try:
            word = GBK2312()
            # word = "十年"
            words = ['十年', '富士山下', '爱情转移', '海阔天空']
            starttime = datetime.datetime.now()
            loop = asyncio.new_event_loop()
            r = loop.run_until_complete(get(words))
            endtime = datetime.datetime.now()
            print(endtime - starttime)
        except Exception as e:
            return HttpResponse(str(e))
        return JsonResponse(r, safe=False)


async def fetch(session, url):
    async with session.get(url) as response:
        return await response.json(content_type=None)


async def get(names):
    # names = ['十年', '富士山下', '爱情转移', '夜曲']
    songss = []
    all_comment = []
    s_c_list = []
    async with aiohttp.ClientSession() as session:
        for name in names:
            songs = await fetch(session,
                                f'http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s={name}&type=1&offset=0&total=true&limit=20')
            songss += songs['result']['songs']
        for song in songss:
            comments = await fetch(session,
                                   f'http://music.163.com/api/v1/resource/comments/R_SO_4_{song["id"]}?limit=100&offset=0')
            # all_comment += comments["hotComments"]
            for c in comments["hotComments"]:
                s_c_list.append({'song_name': song['name'], 'content': c["content"], "pic": c["user"]["avatarUrl"],
                                 "nick": c["user"]["nickname"]})
    return s_c_list
# 下面两行都是套路，记住就好


class zhuanfa1(APIView):

    def get(self, request):
        s_c_list = []
        word = GBK2312()
        # word = "十年"
        print(word)
        search_url = 'http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=' + word + '&type=1&offset=0&total=true&limit=20'
        try:
            data = requests.get(search_url)
            data = data.json()
            songs = data["result"]["songs"]
            op = OP()
            op.flow(songs)

        except Exception as e:
            return JsonResponse(list(op.mp_lst), safe=False)
        print(op.mp_lst)
        return JsonResponse(list(op.mp_lst), safe=False)


class OP():
    def __init__(self):
        # 直接调用 Manager 提供的 list() 和 dict()
        self.manager = mp.Manager
        self.mp_lst = self.manager().list()
        self.mp_dict = self.manager().dict()
        self.length = 64

    def proc_func(self, s):
        # print("执行")
        comments_url = f'https://music.163.com/api/v1/resource/comments/R_SO_4_' + str(s['id']) + '?limit=20&offset=0'
        data = requests.get(comments_url).json()
        comments = data["hotComments"]
        if not comments:
            return
        for c in comments:
            # print(c)
            self.mp_lst.append({'song_name': s['name'], 'content': c["content"], "pic": c["user"]["avatarUrl"],
                                "nick": c["user"]["nickname"]})

    def flow(self, args):
        pool = mp.Pool(len(args))
        for arg in args:
            pool.apply_async(self.proc_func, arg)
        # pool.map(self.proc_func, args)
        pool.close()
        pool.join()
